package com.ljyh.forum.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 安全工具类
 */
public class SecurityUtils {

    /**
     * 获取当前登录用户的用户名
     * @return 用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                return ((UserDetails) principal).getUsername();
            } else if (principal instanceof String) {
                return (String) principal;
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户的ID
     * 需要结合JWT工具类使用
     * @param jwtUtil JWT工具类
     * @return 用户ID
     */
    public static Long getCurrentUserId(com.ljyh.forum.config.JwtUtil jwtUtil) {
        String token = getCurrentToken();
        if (token != null && jwtUtil != null) {
            try {
                return jwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                // token可能无效或过期
                return null;
            }
        }
        return null;
    }

    /**
     * 获取当前请求的JWT token
     * @return JWT token
     */
    public static String getCurrentToken() {
        try {
            // 使用Spring的RequestContextHolder获取当前请求
            jakarta.servlet.http.HttpServletRequest request = 
                ((org.springframework.web.context.request.ServletRequestAttributes) 
                 org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes())
                .getRequest();
            
            // 尝试从Authorization头获取token
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                return authHeader.substring(7);
            }
            
            // 如果Authorization头不存在，尝试从其他常见位置获取
            String token = request.getHeader("X-Auth-Token");
            if (token != null && !token.trim().isEmpty()) {
                return token;
            }
            
            // 尝试从参数中获取
            token = request.getParameter("token");
            if (token != null && !token.trim().isEmpty()) {
                return token;
            }
            
        } catch (Exception e) {
            // 如果不在web请求上下文中，返回null
        }
        return null;
    }

    /**
     * 检查当前用户是否已认证
     * @return 是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() && 
               !(authentication.getPrincipal() instanceof String && 
                 "anonymousUser".equals(authentication.getPrincipal()));
    }
}
